/*
 * General main file outline for Towerhack
 */

#include <stdio.h>
#include <stdlib.h>
#include "resources.h"
#include "main.h"
#include "menu.h"
#include "lobby.h"
#include "game.h"
#include "setup.h"
#include "network.h"
#include "filecheck.h"

int quit = 0;
int global_state;

void update_state ()
{
	if (key[KEY_ESC]) {
			quit = 1;
	}
	switch (global_state) {
		case STATE_MENU:
			menu_update ();
			break;

		case STATE_LOBBY:
			lobby_update();
			network_update();
			break;

		case STATE_GAME:
			game_update();
			network_update();
			break;

		default:
			assert(0);
	}
}

void draw_state ()
{
	switch (global_state) {
		case STATE_UNDEFINED: 
			break;
			
		case STATE_MENU:
			menu_draw ();
			break;
		
		case STATE_LOBBY:
			lobby_draw();
			break;
		case STATE_GAME:
			game_draw();
			break;
		default:
			assert(0);
	}
}

void change_state (int new_state) {
	switch (global_state) {
		case STATE_UNDEFINED: 
			break;
			
		case STATE_MENU:
			menu_cleanup ();
			break;
			
		case STATE_LOBBY:
			lobby_cleanup ();
			break;
			
		case STATE_GAME:
			game_cleanup();
			break;
			
		default:
			assert(0);
	}
	global_state = new_state;
	switch (new_state) {
		case STATE_UNDEFINED: // causes application exit
			quit = 1;
			break;
			
		case STATE_MENU:
			menu_init ();
			break;
		
		case STATE_LOBBY:
			lobby_init ();
			break;
		case STATE_GAME:
			game_init();
			break;
		default:
			assert(0);
	}
}

void main_loop ()
{
        ticks = 0;
        while (!quit) {
                while (ticks > 0) {
                        update_state();
                        ticks--;
                }
                draw_state();
                flip();
                while (ticks <= 0) {
                        rest(1);
                }
        }
}

int main (int argc, char* argv[])
{
	filecheck_batch("filelist.txt");

	quit = 0;
	global_state = STATE_UNDEFINED;

	load_allegro ();
	load_data (); /* from files */
	
	change_state (STATE_MENU); // initial default state
	main_loop ();

	cleanup ();
	fprintf(stderr, "Thanks for 'playing' Towerhack\n");
	return EXIT_SUCCESS;
}
END_OF_MAIN()

